﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace P2P_Backup.connections
{
    public class RemotePeerConnection
    {
        TcpClient tcpClient;
        Thread clientThread;
        bool open;

        public event EventHandler<tools.net.DataEventArgs> dataReceived;
        public event EventHandler disconnect;
        public RemotePeerConnection(IPAddress ipAddress)
        {
            tcpClient = new TcpClient();            
            tcpClient.Connect(ipAddress, P2PBackup.ApplicationPort);
            startClientComm();
        }

        public RemotePeerConnection(TcpClient tcpClient)
        {
            this.tcpClient = tcpClient;

            startClientComm();
        }

        public void sendText(string p)
        {
            try
            {
                byte[] bytes = tools.net.getBytes(p);
                tcpClient.GetStream().Write(bytes, 0, bytes.Length);
                tcpClient.GetStream().Flush();
            }
            catch (Exception e)
            {
                Console.WriteLine("Problem with remote peer connection: {0}", e.Message);
            }
        }

        private void startClientComm()
        {
            open = true;
            clientThread = new Thread(handleCLientComm);
            clientThread.IsBackground = true;
            clientThread.Start();
        }
        private void handleCLientComm()
        {
            NetworkStream clientStream = tcpClient.GetStream();
            byte[] bytes = new byte[4096];
            int bytesRead;

            while (open)
            {
                bytesRead = 0;
                try
                {
                    bytesRead = clientStream.Read(bytes, 0, 4096);
                }
                catch(Exception ex)
                {   
                    if(open) Console.WriteLine(ex.Message);
                    break;
                }
                if (bytesRead == 0)
                {                    
                    break;
                }
                string[] data = tools.net.getDataFromBytes(bytes, bytesRead);
                if (dataReceived != null)
                {
                    dataReceived(this, new tools.net.DataEventArgs(data));
                }                
            }
            if(disconnect!= null) disconnect(this,new EventArgs());
            tcpClient.Close();
        }

        public void Close()
        {
            open = false;
        }
    }
}
